class DBStorage {
  constructor() {
    this.dbName = 'EnglishListeningDB';
    this.dbVersion = 1;
    this.db = null;
  }

  async init() {
    if (this.db) return this.db;

    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.dbVersion);

      request.onerror = () => {
        console.error('IndexedDB打开失败:', request.error);
        reject(request.error);
      };

      request.onsuccess = () => {
        this.db = request.result;
        console.log('IndexedDB初始化成功');
        resolve(this.db);
      };

      request.onupgradeneeded = (event) => {
        const db = event.target.result;

        // 创建文件存储表
        if (!db.objectStoreNames.contains('files')) {
          const fileStore = db.createObjectStore('files', { keyPath: 'id' });
          fileStore.createIndex('name', 'name', { unique: false });
          fileStore.createIndex('type', 'type', { unique: false });
          fileStore.createIndex('timestamp', 'timestamp', { unique: false });
        }

        // 创建播放状态存储表
        if (!db.objectStoreNames.contains('playbackState')) {
          const stateStore = db.createObjectStore('playbackState', { keyPath: 'id' });
          stateStore.createIndex('audioFile', 'audioFile', { unique: false });
          stateStore.createIndex('timestamp', 'timestamp', { unique: false });
        }

        // 创建应用状态存储表
        if (!db.objectStoreNames.contains('appState')) {
          db.createObjectStore('appState', { keyPath: 'key' });
        }

        console.log('IndexedDB数据库结构创建完成');
      };
    });
  }

  // 保存文件到数据库
  async saveFile(file, content, type = 'audio') {
    await this.init();
    
    const fileData = {
      id: `${type}_${file.name}_${file.size}_${file.lastModified}`,
      name: file.name,
      size: file.size,
      lastModified: file.lastModified,
      type: type,
      content: content,
      timestamp: Date.now()
    };

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['files'], 'readwrite');
      const store = transaction.objectStore('files');
      const request = store.put(fileData);

      request.onsuccess = () => {
        console.log(`文件 ${file.name} 已保存到数据库`);
        resolve(fileData.id);
      };

      request.onerror = () => {
        console.error('保存文件失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 从数据库读取文件
  async getFile(fileId) {
    await this.init();

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['files'], 'readonly');
      const store = transaction.objectStore('files');
      const request = store.get(fileId);

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        console.error('读取文件失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 根据文件信息查找是否已缓存
  async findCachedFile(fileName, size, lastModified, type = 'audio') {
    const fileId = `${type}_${fileName}_${size}_${lastModified}`;
    return await this.getFile(fileId);
  }

  // 获取所有缓存的文件
  async getAllFiles() {
    await this.init();

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['files'], 'readonly');
      const store = transaction.objectStore('files');
      const request = store.getAll();

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        console.error('获取文件列表失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 保存播放状态
  async savePlaybackState(audioFileId, state) {
    await this.init();

    const stateData = {
      id: `state_${audioFileId}`,
      audioFile: audioFileId,
      currentTime: state.currentTime || 0,
      playbackRate: state.playbackRate || 1,
      isRepeating: state.isRepeating || false,
      repeatStart: state.repeatStart || null,
      repeatEnd: state.repeatEnd || null,
      selectedSubtitleIndex: state.selectedSubtitleIndex || 0,
      showTranslation: state.showTranslation || false,
      timestamp: Date.now()
    };

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['playbackState'], 'readwrite');
      const store = transaction.objectStore('playbackState');
      const request = store.put(stateData);

      request.onsuccess = () => {
        resolve(stateData);
      };

      request.onerror = () => {
        console.error('保存播放状态失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 读取播放状态
  async getPlaybackState(audioFileId) {
    await this.init();

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['playbackState'], 'readonly');
      const store = transaction.objectStore('playbackState');
      const request = store.get(`state_${audioFileId}`);

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        console.error('读取播放状态失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 保存应用状态（当前选择的文件等）
  async saveAppState(key, value) {
    await this.init();

    const stateData = {
      key: key,
      value: value,
      timestamp: Date.now()
    };

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['appState'], 'readwrite');
      const store = transaction.objectStore('appState');
      const request = store.put(stateData);

      request.onsuccess = () => {
        resolve(stateData);
      };

      request.onerror = () => {
        console.error('保存应用状态失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 读取应用状态
  async getAppState(key) {
    await this.init();

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['appState'], 'readonly');
      const store = transaction.objectStore('appState');
      const request = store.get(key);

      request.onsuccess = () => {
        resolve(request.result?.value || null);
      };

      request.onerror = () => {
        console.error('读取应用状态失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 清理过期数据（超过7天的缓存）
  async cleanExpiredData() {
    await this.init();
    const expireTime = 7 * 24 * 60 * 60 * 1000; // 7天
    const cutoffTime = Date.now() - expireTime;

    // 清理有timestamp索引的存储
    const indexedStores = ['files', 'playbackState'];
    
    for (const storeName of indexedStores) {
      try {
        await new Promise((resolve, reject) => {
          const transaction = this.db.transaction([storeName], 'readwrite');
          const store = transaction.objectStore(storeName);
          
          // 检查是否有timestamp索引
          if (store.indexNames.contains('timestamp')) {
            const index = store.index('timestamp');
            const range = IDBKeyRange.upperBound(cutoffTime);
            const request = index.openCursor(range);

            request.onsuccess = (event) => {
              const cursor = event.target.result;
              if (cursor) {
                cursor.delete();
                cursor.continue();
              } else {
                resolve();
              }
            };

            request.onerror = () => {
              console.error(`清理${storeName}过期数据失败:`, request.error);
              reject(request.error);
            };
          } else {
            // 如果没有索引，直接resolve
            resolve();
          }
        });
      } catch (error) {
        console.warn(`清理${storeName}失败，跳过:`, error);
      }
    }

    // 对于appState，单独处理（没有timestamp索引）
    try {
      await new Promise((resolve, reject) => {
        const transaction = this.db.transaction(['appState'], 'readwrite');
        const store = transaction.objectStore('appState');
        const request = store.getAll();

        request.onsuccess = () => {
          const allRecords = request.result;
          const deletePromises = [];

          for (const record of allRecords) {
            if (record.timestamp && record.timestamp < cutoffTime) {
              const deleteRequest = store.delete(record.key);
              deletePromises.push(new Promise((res, rej) => {
                deleteRequest.onsuccess = () => res();
                deleteRequest.onerror = () => rej(deleteRequest.error);
              }));
            }
          }

          Promise.all(deletePromises).then(() => resolve()).catch(reject);
        };

        request.onerror = () => {
          console.error('清理appState过期数据失败:', request.error);
          reject(request.error);
        };
      });
    } catch (error) {
      console.warn('清理appState失败，跳过:', error);
    }

    console.log('过期数据清理完成');
  }

  // 获取数据库使用情况
  async getStorageInfo() {
    await this.init();
    
    try {
      const files = await this.getAllFiles();
      const totalSize = files.reduce((sum, file) => {
        // 估算文件大小（实际存储可能略有不同）
        return sum + (file.size || 0);
      }, 0);

      return {
        fileCount: files.length,
        totalSize: totalSize,
        formattedSize: this.formatFileSize(totalSize)
      };
    } catch (error) {
      console.error('获取存储信息失败:', error);
      return { fileCount: 0, totalSize: 0, formattedSize: '0 B' };
    }
  }

  // 格式化文件大小显示
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  // 删除特定文件
  async deleteFile(fileId) {
    await this.init();

    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['files'], 'readwrite');
      const store = transaction.objectStore('files');
      const request = store.delete(fileId);

      request.onsuccess = () => {
        console.log(`文件 ${fileId} 已删除`);
        resolve();
      };

      request.onerror = () => {
        console.error('删除文件失败:', request.error);
        reject(request.error);
      };
    });
  }

  // 清空所有数据
  async clearAll() {
    await this.init();
    
    const stores = ['files', 'playbackState', 'appState'];
    
    for (const storeName of stores) {
      await new Promise((resolve, reject) => {
        const transaction = this.db.transaction([storeName], 'readwrite');
        const store = transaction.objectStore(storeName);
        const request = store.clear();

        request.onsuccess = () => resolve();
        request.onerror = () => reject(request.error);
      });
    }

    console.log('所有数据已清空');
  }
}

// 创建单例实例
const dbStorage = new DBStorage();

export default dbStorage;